<template>
  <div class="container">
    <div class="apply-container">
      <div class="apply-container-head"></div>
      <div class="apply-container-body">
        <div class="apply-container-body-title">
          <div class="apply-container-body-title-font">维修申请</div>
          <div class="apply-container-body-title-return">
            <el-button size="small" @click="goBackPage">返回</el-button>
          </div>
        </div>
        <el-divider class="apply-container-body-title-line"></el-divider>
        <div class="apply-container-body-content">
          <el-form :model="RepairOrder" label-width="110px" ref="RepairOrder" label-position="LabelPosition"
            :rules="RepairOrderRules" style="width: 100%;">

            <el-form-item label="姓名:" prop="InputUserName" style="width: 40%;">
              <el-input v-model="RepairOrder.InputUserName" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="工号:" prop="InputUserId" style="width: 40%;">
              <el-input v-model="RepairOrder.InputUserId" placeholder="请输入工号" clearable></el-input>
            </el-form-item>
            <el-form-item label="申请人电话:" prop="InputUserPhone" style="width: 40%;">
              <el-input v-model="RepairOrder.InputUserPhone" placeholder="请输入申请人电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="车牌号:" prop="SelectAutoPlateNum" style="width: 40%;">
              <el-select v-model="RepairOrder.SelectAutoPlateNum" placeholder="请选择车牌号" clearable>
                <el-option v-for="item in RepairOrder.SelectAutoPlateNumOptions" :key="item" :label="item"
                  :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="维修类型:" prop="SelectAutoRepairType" style="width: 40%;">
              <el-select v-model="RepairOrder.SelectAutoRepairType" placeholder="请选择维修类型" clearable>
                <el-option label="汽车大修" value="汽车大修"></el-option>
                <el-option label="汽车总成大修" value="汽车总成大修"></el-option>
                <el-option label="汽车小修" value="汽车小修"></el-option>
                <el-option label="零部件修理" value="零部件修理"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="维修描述:" prop="InputRepairDescribe" style="width: 50%;">
              <el-input v-model="RepairOrder.InputRepairDescribe" type="textarea" placeholder="请输入内容" maxlength="100"
                show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="维修厂:" prop="SelectRepairFactory" style="width: 40%;">
              <el-select v-model="RepairOrder.SelectRepairFactory" placeholder="请选择车牌号" clearable>
                <el-option label="驰加" value="驰加"></el-option>
                <el-option label="华胜汽修" value="华胜汽修"></el-option>
                <el-option label="博世车联" value="博世车联"></el-option>
                <el-option label="车工坊" value="车工坊"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="送修日期:" prop="RepairStartTime" style="width: 40%;">
              <el-date-picker v-model="RepairOrder.RepairStartTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择取车时间" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label="期望取车时间:" prop="RepairEndTime" style="width: 40%;">
              <el-date-picker v-model="RepairOrder.RepairEndTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择期望取车时间" clearable></el-date-picker>
            </el-form-item>
            <div class="apply-container-body-content-submit">
              <el-button type="primary" @click="Submit('RepairOrder')">提交</el-button>
            </div>
          </el-form>
        </div>
      </div>
      <div class="apply-container-footer"></div>
    </div>
  </div>
</template>
  
<script>
import { fetchPlateNums } from '@/api/archives.js'
import { addRepairOrder } from '@/api/application.js'
import { getGeneralUserId } from '@/api/todo.js'
import { getRepairOrderId } from '@/api/application.js'
import { insertTodo } from '@/api/todo.js';
import { getUserInfoById } from '@/api/user.js';
export default {
  name: 'RepairApplicationView',
  data() {
    return {
      LabelPosition: 'right',
      RepairOrder: {
        InputUserName: null,
        InputUserId: null,
        InputUserPhone: null,
        SelectAutoPlateNum: null,
        SelectAutoPlateNumOptions: [],
        SelectAutoRepairType: null,
        InputRepairDescribe: null,
        SelectRepairFactory: null,
        RepairStartTime: null,
        RepairEndTime: null,
        SubmitTime: null,
      },
      RepairOrderRules: {
        InputUserName: [{ required: true, message: '请输入姓名', trigger: 'blur' },],
        InputUserId: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 8, max: 8, message: '工号长度为 8', trigger: 'blur' }
        ],
        InputUserPhone: [
          { required: true, message: '请输入申请人电话', trigger: 'blur' },
          { min: 11, max: 11, message: '电话长度为 11', trigger: 'blur' }
        ],
        SelectAutoPlateNum: [{ required: true, message: '请选择车牌号', trigger: 'change' },],
        SelectAutoRepairType: [{ required: true, message: '请选择车牌号', trigger: 'change' },],
        InputRepairDescribe: [{ required: true, message: '请输入维修描述', trigger: 'blur' },],
        SelectRepairFactory: [{ required: true, message: '请选择维修厂', trigger: 'change' },],
        RepairStartTime: [{ type: 'string', required: true, message: '请输入时间', trigger: 'blur' },],
        RepairEndTime: [{ type: 'string', required: true, message: '请输入时间', trigger: 'blur' },],
      },
      SubmitRepairOrder: {
        userName: null,
        userId: null,
        userPhone: null,
        autoPlateNum: null,
        autoRepairType: null,
        repairDescribe: null,
        repairFactory: null,
        repairStartTime: null,
        repairEndTime: null,
        submitTime: null,
        repairOrderStatus: null,
        repairOrderProgress: null,
      },
      SubmitTodo: {
        userId: null,
        todoTime: null,
        todoType: null,
        orderId: null,
        todoStatus: null,
      },
      GeneralAdminId: null,
      NextUserRole: "综合办",
      RepairOrderId: null,
      SubmitCode: [],
    }
  },

  methods: {
    GetAutoPlateNum() {
      fetchPlateNums().then(res => {
        const temp = res.data.data;
        const result = [];
        temp.forEach(element => { result.push(Object.values(element)) })
        result.forEach(element => { this.RepairOrder.SelectAutoPlateNumOptions.push(element[1]) });
      }).catch((err) => {
        console.log(err);
      })
    },
    UpdateCurrentTime() {
      const currentDateTime = new Date();
      const dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' };
      const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
      const formattedDate = currentDateTime.toLocaleDateString(undefined, dateOptions);
      const formattedTime = currentDateTime.toLocaleTimeString(undefined, timeOptions);
      this.RepairOrder.SubmitTime = `${formattedDate} ${formattedTime}`;
    },
    AddRepairOrder() {
      return new Promise((resolve, reject) => {
        this.SubmitRepairOrder.userName = this.RepairOrder.InputUserName;
        this.SubmitRepairOrder.userId = this.RepairOrder.InputUserId;
        this.SubmitRepairOrder.userPhone = this.RepairOrder.InputUserPhone;
        this.SubmitRepairOrder.autoPlateNum = this.RepairOrder.SelectAutoPlateNum;
        this.SubmitRepairOrder.autoRepairType = this.RepairOrder.SelectAutoRepairType;
        this.SubmitRepairOrder.repairDescribe = this.RepairOrder.InputRepairDescribe;
        this.SubmitRepairOrder.repairFactory = this.RepairOrder.SelectRepairFactory;
        this.SubmitRepairOrder.repairStartTime = this.RepairOrder.RepairStartTime;
        this.SubmitRepairOrder.repairEndTime = this.RepairOrder.RepairEndTime;
        this.SubmitRepairOrder.submitTime = this.RepairOrder.SubmitTime;
        this.SubmitRepairOrder.repairOrderStatus = "流转中";
        this.SubmitRepairOrder.repairOrderProgress = 1;
        addRepairOrder(this.SubmitRepairOrder)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    GetGeneralUserId() {
      return new Promise((resolve, reject) => {
        getGeneralUserId()
          .then(res => {
            const temp = res.data.data;
            const result = Object.values(temp);
            this.GeneralAdminId = result[0];
            resolve(); // 表示异步操作成功
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    GetRepairOrderId() {
      return new Promise((resolve, reject) => {
        getRepairOrderId(this.SubmitRepairOrder.submitTime)
          .then(res => {
            const temp = res.data.data;
            const result = Object.values(temp);
            this.RepairOrderId = result[0];
            resolve(); // 表示异步操作成功
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    AddTodo() {
      return new Promise((resolve, reject) => {
        this.SubmitTodo.userId = this.GeneralAdminId;
        this.SubmitTodo.todoTime = this.RepairOrder.SubmitTime;
        this.SubmitTodo.todoType = "维修申请综合办审批";
        this.SubmitTodo.orderId = this.RepairOrderId; // 待工单提交到数据库后从后端获取
        this.SubmitTodo.todoStatus = '未完成';
        insertTodo(this.SubmitTodo)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    //检错，可复用
    JudgeSubmitCode(data) {
      const allZeros = data.every(code => code === '0');
      return allZeros;
    },
    showMessage(message, type) {
      this.$message({
        message: message,
        duration: 2000,
        showClose: true,
        type: type,
      });
    },
    goBackPage() {
      this.$router.go(-1)
    },
    JudgeSuccess(data) {
      if (this.JudgeSubmitCode(data)) {
        this.showMessage('新建申请成功!', 'success');
        this.goBackPage();
      } else
        this.showMessage('新建申请失败!', 'error');
    },
    Submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将提交该维修申请, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.UpdateCurrentTime();
            this.AddRepairOrder()
              .then(() => this.GetGeneralUserId())
              .then(() => this.GetRepairOrderId())
              .then(() => this.AddTodo())
              .then(() => {
                this.JudgeSuccess(this.SubmitCode);
              })
              .catch(error => {
                console.log(error);
                this.$message.error('提交失败: ' + error);
              });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
        else {
          return false;
        }
      })
    },
    InitData() {
      return new Promise((resolve, reject) => {
        try {
          getUserInfoById(localStorage.getItem("userId")).then(res => {
            const data = res.data.data;
            this.RepairOrder.InputUserName = data[0].userName;
            this.RepairOrder.InputUserId = data[0].userId;
            this.RepairOrder.InputUserPhone = data[0].userPhone;
          })
          resolve(); // 表示异步操作成功
        } catch (error) {
          console.log(error);
          reject(error); // 处理异步错误
        }
      });
    },
  },

  created() {
    this.GetAutoPlateNum();
    this.InitData();
  },
}
</script>
  
<style scoped>
.container {
  /* height: 100%; */
  width: 95%;
  margin: 0 auto;
  margin-top: 1%;
  background-color: #ffffff;
}

.apply-container {
  width: 90%;
  height: 100%;
  margin: 0 auto;
  /* background-color: #f2f2f2; */

}

.apply-container-head {
  width: 95%;
  height: 30px;
  margin: 0 auto;
}

.apply-container-body {
  width: 95%;
  height: 92%;
  margin: 0 auto;
  background-color: #ffffff;

}

.apply-container-body-title {
  width: 98%;
  height: 5%;
  margin: 0 auto;
  display: flex;
}

.apply-container-body-title-return {
  width: 100%;
  padding-top: 5px;
  display: flex;
  justify-content: flex-end;
}

.apply-container-body-title-line {
  height: 1px;
  width: 98%;
  margin: 5px auto;
}

.apply-container-body-title-font {
  width: 100%;
  height: 99%;
  font-size: 18px;
  font-weight: bold;
  text-align: left;
  padding-top: 10px;
}

.apply-container-body-content {
  width: 85%;
  height: 100%;
  margin: 20px auto;
  display: flex;

}

.apply-container-body-content-submit {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.apply-container-footer {
  width: 95%;
  height: 10px;
  margin: 0 auto;
}
</style>